﻿using System;
using System.Windows;
using System.Windows.Navigation;
using SoftwareLogistics.SharepointClient.Library;
using System.Windows.Controls;
using SoftwareLogistics.SharepointClient.Library.Models;

namespace SoftwareLogistics.SharepointClient.Silverlight
{
    public partial class Home : Page
    {
        private const string STR_UserName = "UserName";
        private const string STR_UsersPlainTextPassword = "UsersPlainTextPassword";
        public Home()
        {
            InitializeComponent();
            Common.AuthService.Authenticated += (sender, args) =>
            {
                Dispatcher.BeginInvoke(() =>
                {
                    Common.StateBag[STR_UserName] = UserName.Text;
                    if (SavePassword.IsChecked.HasValue && SavePassword.IsChecked.Value)
                        Common.StateBag[STR_UsersPlainTextPassword] = Password.Password;
                    else if (Common.StateBag.ContainsKey(STR_UsersPlainTextPassword))
                        Common.StateBag.Remove(STR_UsersPlainTextPassword);

                    Common.SaveStateBag();
                });

                Common.Users.GetUsers();
            };

            Common.AuthService.FailedAuthentication += (sender, args) =>
            {
                Dispatcher.BeginInvoke(() =>
                {
                    App.ProgressDialog.Close();
                    MessageBox.Show("Invalid credentials, please try again.");

                    Password.Password = string.Empty;
                });
            };

            Common.Users.GotUsers += (sender, args) =>
            {
                Common.SyncService.SyncNow("pm");
           };

            Common.SyncService.SyncCompleted += (sender, args) =>
            {
                Dispatcher.BeginInvoke(() =>
                {
                    App.ProgressDialog.Close();
                    Common.Users.SetCurrentUser(UserName.Text);
                    NavigationService.Navigate(new Uri("/Main", UriKind.Relative));
                });
            };
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (Common.StateBag.ContainsKey(STR_UserName))
                UserName.Text = Common.StateBag[STR_UserName];

            if (Common.StateBag.ContainsKey(STR_UsersPlainTextPassword))
            {
                Password.Password = Common.StateBag[STR_UsersPlainTextPassword];
                SavePassword.IsChecked = true;
            }
        }

        private void Login_Click(object sender, RoutedEventArgs e)
        {
            Common.AuthService.Auth(UserName.Text, Password.Password);
            App.ProgressDialog.Show();
        }
    }
}